#!/usr/bin/python3
# -*- coding: utf-8 -*
import requests
import pymysql
import datetime
import time
mysql_host = '47.96.38.186'
mysql_password = 'dmxy456258'


# 在动态中获取对应的更新，一次大概会刷新17条
def getUpdateList():
    video_titles=[]
    author_names=[]
    links=[]
    url = "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/all?timezone_offset=-480&type=video&platform=web&page=1&features=itemOpusStyle,listOnlyfans,opusBigCover&web_location=444.41"
    payload = {}
    headers = {
        'authority': 'api.bilibili.com',
        'accept': '*/*',
        'accept-language': 'en-US,en;q=0.9,zh-TW;q=0.8,zh-CN;q=0.7,zh;q=0.6',
        'cache-control': 'no-cache',
        'cookie': 'buvid3=F2B95DB1-D255-D7CA-070D-56ADC0B3307546612infoc; b_nut=1699352746; CURRENT_FNVAL=4048; _uuid=6A1028107D-694A-6967-44DE-5538AD32DF5279128infoc; buvid_fp=cc68dac4addd9ac6d4a96321735c8e08; buvid4=35E1576E-F886-6E45-78C5-1C40B5034D5A78813-023110910-BgNyseuAzccAFS%2BzOWikLw%3D%3D; rpdid=|(ummm|lRlJ~0J\'uYmmRmY)~m; hit-dyn-v2=1; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDA3MDYwNjMsImlhdCI6MTcwMDQ0NjgwMywicGx0IjotMX0.tnemd5BuI3bnDxM-6dEskHynjk3pyavpeYXAuAESDdk; bili_ticket_expires=1700706003; b_lsid=8D10E2CAA_18BEBA78718; PVID=1; SESSDATA=8bb1eae2%2C1716018931%2C5c646%2Ab2CjCevDuPj4Qd__H8LKcjfOt242VqrweBX1MHEisfoBv2UFppjyIBXuV_WWvPVprz2MISVnV0NnV4SDY4bHQ2czRVdjRkOEtYNE1jcWJ6VUJEUzZYZTBrZ3QxZWx1bVZpTkVocjd4R2l0YTZ4bmZMR2VyRDctM1I0MmFEdXpUYzZDTnBmSXluMjZnIIEC; bili_jct=ff2c7684c0f9f60aeae1f052b3005e6a; DedeUserID=80721790; DedeUserID__ckMd5=6593fcf42b644d33; sid=plhutjme',
        'origin': 'https://t.bilibili.com',
        'pragma': 'no-cache',
        'referer': 'https://t.bilibili.com/?tab=video',
        'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36'
    }
    try:
        response = requests.request("GET", url, headers=headers, data=payload)
        #获取列表中的每个视频信息
        items_lists = response.json()['data']['items']
        # 获取视频标题
        for video_title_iterator in items_lists:
            video_title = video_title_iterator['modules']['module_dynamic']['major']['archive']['title']
            video_titles.append(video_title)
        # 获取作者名称
        for author_name_iterator in items_lists:
            author_name = author_name_iterator['modules']['module_author']['name']
            author_names.append(author_name)
        # 获取跳转链接
        for link_iterator in items_lists:
            link = link_iterator['modules']['module_dynamic']['major']['archive']['jump_url']
            link = link[2:]
            links.append(link)
        return video_titles,author_names,links
    except Exception as e:
        webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=67e62638-af00-4879-a146-b468fd718a30'
        print(str(e))
        data = {'msgtype': 'text', 'text': {'content': 'touch_fish.py脚本运行失败'}}
        response = requests.post(webhook_url,json=data)
        print(response)

# 判断是否为不提醒的up主，是→返回true  不是→返回false
def isBlockAuthor(author_name):
    db = pymysql.connect(host=mysql_host, user='root', password=mysql_password, database='touch_fish')
    cursor = db.cursor()
    sql = f"SELECT * FROM block_author_name where author_name='{author_name}'"
    cursor.execute(sql)
    data = cursor.fetchall()
    # 结果为空
    if len(data) == 0:
        return False
    # 结果不为空，继续处理
    else:
        return True
    cursor.close()
    db.close()

def sendNotice(author_name,video_title,link):
    webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=67e62638-af00-4879-a146-b468fd718a30'
    # 发送消息
    data = {'msgtype': 'text', 'text': {'content': f'视频更新提示\nup主：{author_name}\n{video_title}\n点击开始摸鱼{link}'}}
    response = requests.post(webhook_url, json=data)
    print(response.json())

# 保存已经提醒过的消息，并做对比防止重复提醒
def saveNotice(link):
    db = pymysql.connect(host=mysql_host, user='root', password=mysql_password, database='touch_fish')
    cursor = db.cursor()
    notice_time = int(time.mktime(datetime.datetime.now().timetuple()))
    print(notice_time)
    sql = f"INSERT INTO hasnotice (link, notice_time) VALUES ('{link}', {notice_time});"
    cursor.execute(sql)
    db.commit()
    cursor.close()
    db.close()

# 判断是否提醒过 提醒过→True 未提醒→False
def hasNotice(link):
    db = pymysql.connect(host=mysql_host, user='root', password=mysql_password, database='touch_fish')
    cursor = db.cursor()
    sql = f"SELECT * FROM hasnotice where link='{link}'"
    cursor.execute(sql)
    data = cursor.fetchall()
    # 结果为空
    if len(data) == 0:
        return False
    # 结果不为空，继续处理
    else:
        return True
    cursor.close()
    db.close()


if __name__ == '__main__':
    try:
        video_titles,author_names,links = getUpdateList()
        for author_name in author_names:
            if isBlockAuthor(author_name)==False:
                index = author_names.index(author_name)
                video_title = video_titles[index]
                link = links[index]
                if hasNotice(link)!=True:
                    sendNotice(author_name,video_title,link)
                    saveNotice(link)
            else:
                continue
    except Exception as e:
        webhook_url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=67e62638-af00-4879-a146-b468fd718a30'
        print(str(e))
        data = {'msgtype': 'text', 'text': {'content': 'touch_fish.py脚本运行失败'}}
        response = requests.post(webhook_url,json=data)
        print(response)



